import { useEffect, useState, forwardRef, useImperativeHandle } from "react";
import { request } from "@/utils/request.ts";

import styled from "./captcha.module.css";

const Captcha = forwardRef((_, ref) => {
  const [state, setState] = useState({
    captchaId: "",
    data: "",
  });

  const refresh = () => {
    request
      .get<{ captchaId: string; data: string }>("/admin/base/open/captcha")
      .then((resp) => {
        setState({
          captchaId: resp.captchaId,
          data: resp.data,
        });
      });
  };

  useEffect(() => {
    // 默认调用一次 refresh
    refresh();
  }, []);

  // 使用 useImperativeHandle 控制对外的暴露
  useImperativeHandle(
    ref,
    () => ({
      get() {
        return state.captchaId;
      },
      refresh
    }),
    [state]
  );

  return (
    <div
      className={styled.box}
      dangerouslySetInnerHTML={{ __html: state.data }}
      onClick={refresh}
    />
  );
});

export default Captcha;
